package com.thfw.test.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;


/**
 * Created by litingwei on 2018/5/10.
 */

public class AudioPlayManager implements SensorEventListener {

    private Context context;

    private SensorManager sensorManager;
    private Sensor proximity;

    private PowerManager powerManager;
    private PowerManager.WakeLock wakeLock;

    private AudioManager audioManager;
    private int originalAudioMode;
    private int originalStreamVolume;

    private MediaPlayer voiceMediaPlayer;
    private boolean playingAudio = false;

    private AudioPlayListener audioPlayListener;

    @SuppressLint("InvalidWakeLockTag")
    public AudioPlayManager(Context context) {
        this.context = context;
        //
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        proximity = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        //
        powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "TAG");
        wakeLock.setReferenceCounted(false);
        //
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    }

    public void setAudioPlayListener(AudioPlayListener audioPlayListener) {
        this.audioPlayListener = audioPlayListener;
    }

    public void registerSensor() {
        sensorManager.registerListener(this, proximity, SensorManager.SENSOR_DELAY_FASTEST);
    }

    public void unregisterSensor() {
        sensorManager.unregisterListener(this);
    }

    public void startOrStop(String path) {
        if (playingAudio) {
            stop();
            if (audioPlayListener != null) {
                audioPlayListener.stopPlay();
            }
        } else {
            start(path);
        }
    }

    public void start(String path) {
        if (voiceMediaPlayer == null) {
            voiceMediaPlayer = new MediaPlayer();
        } else {
            voiceMediaPlayer.stop();
            voiceMediaPlayer.reset();
        }
        originalAudioMode = audioManager.getMode();
        originalStreamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        audioManager.setSpeakerphoneOn(true);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_VIBRATE);
        voiceMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            voiceMediaPlayer.setDataSource(path);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showToast(context, "音频播放失败");
            if (audioPlayListener != null) {
                audioPlayListener.stopPlay();
            }
            return;
        }
        voiceMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (voiceMediaPlayer != null) {
                    if (!playingAudio) {
                        long delayTime = Build.VERSION.SDK_INT < Build.VERSION_CODES.M ? 2000 : 0;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                voiceMediaPlayer.start();
                                playingAudio = true;
                                wakeLock.acquire();
                            }
                        }, delayTime);
                    } else {
                        voiceMediaPlayer.seekTo(0);
                    }
                }
            }
        });
        voiceMediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete(MediaPlayer mp) {
                voiceMediaPlayer.start();
            }
        });
        voiceMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stop();
                if (audioPlayListener != null) {
                    audioPlayListener.stopPlay();
                }
            }
        });
        voiceMediaPlayer.prepareAsync();
        /*if (audioPlayListener != null) {
            audioPlayListener.startPlay();
        }*/
    }

    public void stop() {
        if (playingAudio && voiceMediaPlayer != null) {
            audioManager.setMode(originalAudioMode);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalStreamVolume, AudioManager.FLAG_VIBRATE);
            voiceMediaPlayer.stop();
            voiceMediaPlayer.reset();
            playingAudio = false;
            if (wakeLock != null) {
                wakeLock.release();
            }
        }
    }

    public void destroy() {
        stop();
        context = null;
        audioManager = null;
        sensorManager = null;
        proximity = null;
        powerManager = null;
        wakeLock = null;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (voiceMediaPlayer == null || audioManager == null || !playingAudio) {
            return;
        }
        float distance = event.values[0];
        Log.i("MsgSendListAdapter", "distance: " + distance);
        if (distance == proximity.getMaximumRange()) {
            audioManager.setSpeakerphoneOn(true);
            if (voiceMediaPlayer.isPlaying() && playingAudio) {
                voiceMediaPlayer.pause();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (voiceMediaPlayer != null && playingAudio && !voiceMediaPlayer.isPlaying()) {
                            voiceMediaPlayer.start();
                        }
                    }
                }, 3000);
            }
        } else {
            audioManager.setSpeakerphoneOn(false);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                    audioManager.getStreamMaxVolume(AudioManager.MODE_IN_COMMUNICATION),
                    AudioManager.FX_KEY_CLICK);
            if (voiceMediaPlayer.isPlaying() && playingAudio) {
                voiceMediaPlayer.stop();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        voiceMediaPlayer.prepareAsync();
                    }
                }, 1000);
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public interface AudioPlayListener {
        void startPlay();
        void stopPlay();
    }

}
